package com.cloudcc.mobile.network;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.entity.AddImageInfo;
import com.cloudcc.mobile.entity.Image;
import com.cloudcc.mobile.entity.ImageInfo;
import com.cloudcc.mobile.entity.CustomerEntity;
import com.cloudcc.mobile.entity.Khbf;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostD;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostF;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostL;
import com.cloudcc.mobile.entity.chat.DraftBox;
import com.cloudcc.mobile.entity.chat.DraftKhbf;
import com.cloudcc.mobile.entity.comment.AddMicroComment;
import com.cloudcc.mobile.entity.comment.AddMicroCommentMessage;
import com.cloudcc.mobile.entity.map.MapLocation;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.parser.AddMicroCommentParser;
import com.cloudcc.mobile.parser.ImageParser;
import com.cloudcc.mobile.parser.KhbfParser;
import com.cloudcc.mobile.parser.ReturnCodeParser;
import com.cloudcc.mobile.util.Json;
import com.cloudcc.mobile.util.NetWork;
import com.cloudcc.mobile.util.NotificationUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

/**
 * 后台发送数据
 * 
 * @author Administrator
 * 
 */
public class QiaoDaoNetWork {
	private Context context;
	private int num;
	private List<String> pzlist;
	List<AddImageInfo> list;
	CustomerEntity kehu;
	MapLocation location;

	AddMicroPostD addMicroPostD;
	AddMicroPostF addMicroPostF;
	AddMicroPostL addMicroPostL;
	AddMicroComment addMicroComment;
	String data;

	String text;
	private int a = 0;
	private int b = 0;

	public QiaoDaoNetWork(Context context, int num) {
		this.context = context;
		this.num = num;
		pzlist = new ArrayList<String>();
	}

	/**
	 * 后台发送签到
	 */
	public void sendQianDao(List<AddImageInfo> list, MapLocation location,
			CustomerEntity kehu, String text) {
		NotificationUtils.showNotification(context, "发送中...", "签到", "签到发送中...",
				num);
		this.list = list;
		this.location = location;
		this.kehu = kehu;
		this.text = text;
		send();
	}

	/**
	 * 后台发送"回复"
	 */
	public void sendComment(AddMicroComment addMicroComment) {
		NotificationUtils.showNotification(context, "发送中...", "微贴", "微贴发送中...",
				num);
		this.addMicroComment = addMicroComment;
		String data = Json.toJson(addMicroComment);
		new MyTask().execute(data);
	}

	/** * 添加评论 */
	class MyTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params) {
			String data = params[0];
			String json = null;
			// String json=serivice.addMicroComment(data);
			List<NameValuePair> pairs = new ArrayList<NameValuePair>();
			pairs.add(new BasicNameValuePair("serviceName",
					AppContext.ADDMICCOMMENT));
			pairs.add(new BasicNameValuePair("data", data));
			pairs.add(new BasicNameValuePair("binding", AppContext.binding));
			String url = UrlTools.url + UrlTools.url_path;
			json = NetWork.post(url, pairs);
			return json;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			try {
				if (result == null || result.equals("NetworkError")) {
					SaveCaoGao();
					NotificationUtils.clearNotification(context, num);
					Tools.showInfo(context, "网络异常,回复已保存到草稿箱");
					return;
				}
				if (result.equals("outTime")) {
					SaveCaoGao();
					NotificationUtils.clearNotification(context, num);
					Tools.showInfo(context, "网络超时,回复已经保存到草稿箱");
					return;
				}
				String code = ReturnCodeParser.getReturnCode(result);
				if (code.equals("-2")) {
					try {
						saveDraftBox();
					} catch (Exception e) {
						Tools.handle(e);
					}
					NotificationUtils.clearNotification(context, num);
					Tools.showInfo(context, "登陆超时,请重新登陆");
					return;
				}
				AddMicroCommentMessage msg = AddMicroCommentParser
						.addmicrocommnet(result);
				String id = msg.getId();
				if (id.equals("") || id == null || id.equals(null)) {
					Tools.showInfo(context, "亲~，此贴已被删除,请刷新数据");
					NotificationUtils.clearNotification(context, num);
					Intent intent = new Intent(AppContext.INDEXADAPTER_SHUAXIN);
					context.sendBroadcast(intent);
					return;
				}
				boolean flag = msg.isResult();
				if (flag) {
					Tools.showInfo(context, "回复成功");
					NotificationUtils.clearNotification(context, num);
				} else {
					SaveCaoGao();
					NotificationUtils.clearNotification(context, num);
					Tools.showInfo(context, "回复失败,已经保存到草稿箱");
				}
			} catch (Exception e) {
				Tools.handle(e);
			}
		}
	}

	/** * 把回复保存到草稿箱 */
	private void SaveCaoGao() {
		try {
			saveDraftComment();
		} catch (DbException e) {
			Tools.handle(e);
		}
		Intent caogao = new Intent(AppContext.CAOGAO_NUM);
		context.sendBroadcast(caogao);
	}

	/** * 把回复保存到数据库 */
	private void saveDraftComment() throws DbException {
		DbUtils db = DbUtils.create(context,
				UserManager.getManager().getUser().userId + "box.db");
		DraftBox box = new DraftBox();
		box.setType("3");
		box.setTime(Tools.getTime(System.currentTimeMillis()));
		box.setIsNew("1");
		box.setLeixing(AppContext.ADDMICCOMMENT);
		addMicroComment.setParent(box);
		box.setComment(addMicroComment);
		db.saveBindingId(addMicroComment);
	}

	protected void send() {

		if (Tools.isNull(text)) {
			text = "我拜访了这个客户！";
		}
		for (int i = 0; i < list.size(); i++) {
			File file = new File(list.get(i).getImagePath());
			if (!file.exists()) {
				list.remove(i);
			}
		}
		if (list.size() > 0) {// 有图
			for (int i = 0; i < list.size(); i++) {
				Image image = new Image(Tools.getTimeName(System
						.currentTimeMillis()), "png", "", "", "");
				final String data = Json.toJson(image);
				final String imgpath = list.get(i).getImagePath();
				new Thread() {
					public void run() {
						try {
							String result = null;
							handler.sendEmptyMessage(-1);
							String Data = URLDecoder.decode(data, "UTF-8");
							final String url = UrlTools.url
									+ UrlTools.imgupload_path + Data
									+ "&binding=" + AppContext.binding;
							result = NetWork.uploadFile(url, imgpath);
							Tools.i("handler", "上传：" + result);
							if (result != null) {
								Message msg = handler.obtainMessage(1);
								msg.obj = result;
								msg.sendToTarget();
							} else {
								handler.obtainMessage(-3);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}.start();
			}
		} else {
			// dialog.show();
			handler.sendEmptyMessage(2);
		}

	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				String result = (String) msg.obj;
				if (Tools.isNull(result)) {
					NotificationUtils.clearNotification(context, num);
					// Intent finish=new Intent(AppContext.MAP_ACTIVITY_FINISH);
					// context.sendBroadcast(finish);
					Intent caogao = new Intent(AppContext.CAOGAO_NUM);
					context.sendBroadcast(caogao);
					Tools.showInfo(context, "签到失败！已保存草稿箱");
					return;
				}
				ImageInfo info = ImageParser.getImageInfo(result);
				boolean isresult = info.isResult();
				if (isresult) {
					pzlist.add(info.getImgId());
					++a;
					b++;
					if (a == list.size()) {
						addkhbf();
					}
				} else {
					++a;
					if (a == list.size()) {
						addkhbf();
					}
				}
				break;
			case -1:
				// dialog.show();
				break;
			case 2:
				addkhbf();
				break;
			case -3:
				NotificationUtils.clearNotification(context, num);
				// Intent finish=new Intent(AppContext.MAP_ACTIVITY_FINISH);
				// context.sendBroadcast(finish);
				Intent caogao = new Intent(AppContext.CAOGAO_NUM);
				context.sendBroadcast(caogao);
				Tools.showInfo(context, "签到失败！已保存草稿箱");
				break;
			}
			super.handleMessage(msg);
		}
	};

	private void saveDraftBox() throws DbException {
		DbUtils db = DbUtils.create(context,
				UserManager.getManager().getUser().userId + "box.db");
		DraftBox box = new DraftBox();
		box.setType("1");
		box.setTime(Tools.getTime(System.currentTimeMillis()));
		box.setIsNew("1");
		DraftKhbf khbf = new DraftKhbf();
		khbf.setPznum(list.size());
		khbf.setBfText(text);
		khbf.setBfTime(Tools.getTime(System.currentTimeMillis()));
		khbf.setBfwz(location.getAddress());
		khbf.setKehuName(kehu.getName());
		khbf.setKehuId(kehu.getId());
		khbf.setParent(box);
		String pz = "";
		if (list.size() > 0) {
			pz = list.get(0).getImagePath();
			for (int i = 1; i < list.size(); i++) {
				pz = pz + "," + list.get(i).getImagePath();
			}
		}
		khbf.setPz(pz);
		box.setKhbf(khbf);
		db.saveBindingId(khbf);
	}

	protected void addkhbf() {
		Khbf khbf = new Khbf();
		khbf.setBfkhccname(kehu.getName());
		khbf.setBfkh(kehu.getId());
		khbf.setBfzj(text);
		khbf.setBfsj(Tools.getTime(System.currentTimeMillis()));
		khbf.setBflx("临时拜访");
		if (list.size() > 0) {
			for (int i = 0; i < 9; i++) {
				if (pzlist.size() < i + 1) {
					pzlist.add("");
				}
			}
			khbf.setPz(pzlist.get(0));
			khbf.setPz1(pzlist.get(1));
			khbf.setPz2(pzlist.get(2));
			khbf.setPz3(pzlist.get(3));
			khbf.setPz4(pzlist.get(4));
			khbf.setPz5(pzlist.get(5));
			khbf.setPz6(pzlist.get(6));
			khbf.setPz7(pzlist.get(7));
			khbf.setPz8(pzlist.get(8));
		}
		khbf.setBfwz(location.getAddress());
		String jsonString = Json.toJson(khbf);
		String Data = null;
		try {
			Data = URLEncoder.encode(jsonString, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}// 这个是对json数据转编码，必须的
		String url = UrlTools.url + UrlTools.url_path
				+ "serviceName=insertWithRoleRight&objectApiName=khbf&data=["
				+ Data + "]&binding=" + AppContext.binding;
		HttpUtils http = new HttpUtils();
		http.configTimeout(15000);
		http.configSoTimeout(15000);
		http.send(HttpRequest.HttpMethod.GET, url,
				new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// dialog.dismiss();
						boolean msg = KhbfParser
								.getUpResult(responseInfo.result);
						if (msg) {
							// for (int i = 0; i < list.size(); i++) {
							// FileUtil.deleteFile(list.get(i).getImagePath());
							// }
							NotificationUtils.clearNotification(context, num);
							// Intent finish=new
							// Intent(AppContext.MAP_ACTIVITY_FINISH);
							// context.sendBroadcast(finish);
							Tools.showInfo(context, "签到成功！");
						} else {
							NotificationUtils.clearNotification(context, num);
							try {
								saveDraftBox();
							} catch (DbException e) {
								e.printStackTrace();
							}
							// Intent finish=new
							// Intent(AppContext.MAP_ACTIVITY_FINISH);
							// context.sendBroadcast(finish);
							Intent caogao = new Intent(AppContext.CAOGAO_NUM);
							context.sendBroadcast(caogao);
							Tools.showInfo(context, "签到失败！已保存草稿箱");
						}
					}

					@Override
					public void onStart() {
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						try {
							NotificationUtils.clearNotification(context, num);
							saveDraftBox();
							// Intent finish=new
							// Intent(AppContext.MAP_ACTIVITY_FINISH);
							// context.sendBroadcast(finish);
							Intent caogao = new Intent(AppContext.CAOGAO_NUM);
							context.sendBroadcast(caogao);
							Tools.showInfo(context, "签到失败！已保存草稿箱");
						} catch (DbException e) {
							e.printStackTrace();
						}
					}
				});

	}

}
